/** @dtcloud-module **/

/**
 * Mock Test Utils
 *
 * This module defines various utility functions to help mocking data.
 *
 * Note that all methods defined in this module are exported in the main
 * testUtils file.
 */

import { patchDate } from "@web/../tests/helpers/utils";

//------------------------------------------------------------------------------
// Public functions
//------------------------------------------------------------------------------

/**
 * intercepts an event bubbling up the widget hierarchy. The event intercepted
 * must be a "custom event", i.e. an event generated by the method 'trigger_up'.
 *
 * Note that this method really intercepts the event if @propagate is not set.
 * It will not be propagated further, and even the handlers on the target will
 * not fire.
 *
 * @param {Widget} widget the target widget (any DTCloud widget)
 * @param {string} eventName description of the event
 * @param {function} fn callback executed when the even is intercepted
 * @param {boolean} [propagate=false]
 */
function intercept(widget, eventName, fn, propagate) {
    var _trigger_up = widget._trigger_up.bind(widget);
    widget._trigger_up = function (event) {
        if (event.name === eventName) {
            fn(event);
            if (!propagate) { return; }
        }
        _trigger_up(event);
    };
}

/**
 * Patch window.Date so that the time starts its flow from the provided Date.
 *
 * Usage:
 *
 *  ```
 *  testUtils.mock.patchDate(2018, 0, 10, 17, 59, 30)
 *  new window.Date(); // "Wed Jan 10 2018 17:59:30 GMT+0100 (Central European Standard Time)"
 *  ... // 5 hours delay
 *  new window.Date(); // "Wed Jan 10 2018 22:59:30 GMT+0100 (Central European Standard Time)"
 *  ```
 *
 * The returned function is there to preserve the former API. Before it was
 * necessary to call that function to unpatch the date. Now the unpatch is
 * done automatically via a call to registerCleanup.
 *
 * @param {integer} year
 * @param {integer} month index of the month, starting from zero.
 * @param {integer} day the day of the month.
 * @param {integer} hours the digits for hours (24h)
 * @param {integer} minutes
 * @param {integer} seconds
 * @returns {Function} callback function is now useless
 */
function legacyPatchDate(year, month, day, hours, minutes, seconds) {
    patchDate(year, month, day, hours, minutes, seconds);
    return function () {}; // all calls to that function are now useless
}

export default {
    intercept: intercept,
    patchDate: legacyPatchDate,
};
